<?php


namespace App\Services;


use App\Models\CompanyManagement;
use App\Models\Management;
use App\Repositories\ManagementRepository;

class LoginService extends BaseService
{

    protected $repository;

    public function __construct()
    {
        $this->repository = new ManagementRepository();
    }


    /**
     * 公司管理员登陆
     * @param string $userName 用户名
     * @param string $password 密码
     * @return array
     * @throws \App\Exceptions\BobException
     * @Author 姿势就是力量
     */
    public function companyLogin(string $userName, string $password)
    {
        $user = $this->repository->firstBy('username', $userName);

//        dd($userName);die();
        if (!$user) return_bob('未找到该用户');
        if (!password_verify($password,$user->password)) return_bob('密码不正确,请重新输入');

        return $this->respondWithToken($user);
    }


    /**
     * 获取登陆TOKEN令牌
     * @param Management $user
     * @return array
     * @throws \App\Exceptions\BobException
     * @Author 姿势就是力量
     */
    protected function respondWithToken(Management $user): array
    {
        // 直接创建token并设置有效期
        $createToken = $user->createToken($user->password);
        $createToken->token->expires_at = now()->addDays(30);
        $createToken->token->save();

        // 管理员所属公司存入SESSION
        $company = (new CompanyManagement())->where('management_id', $user->id)->get()->toArray();
        if (!$company) return_bob('该管理员未绑定公司');
        $companyIds = array_column($company, 'company_id');
        session()->put('companyIds', $companyIds);
        $admin = [
            'id' => $user->id,
            'name' => $user->name,
            'username' => $user->username,
            'phone' => $user->phone,
            'avatar' => $user->avatar,
        ];
        session()->put('adminInfo', $admin);

        return [
            'token' => $createToken->accessToken,
            'token_type' => 'Bearer',
            'user' => $admin,
            'expires_in' => now()->addDays(30)
        ];
    }
}
